import { login, logout, getInfo } from '@/api/login'
import { getToken, setToken, removeToken,
  setAuthUserInfo, removeAuthUserInfo,
  setInitUser, removeInitUser,
 } from '@/utils/auth'

const user = {
  state: {
    token: getToken(),
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    }
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {

      return new Promise((resolve, reject) => {

        login(userInfo.pwForm, userInfo.codeForm, userInfo.loginActive).then(response => {
          const data = response.data;
          setInitUser(data)
          setToken('Bearer '+ data.oauth2AccessToken.access_token)
          commit('SET_TOKEN', 'Bearer '+ data.oauth2AccessToken.access_token)
          resolve(data)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户信息
    GetInfo({ commit, state}) {
      // return new Promise((resolve, reject) => {
      //   console.log('23333333')
      //   getInfo(state.token).then(response => {
      //     console.log('2222222222222')
      //     console.log(response.data)
      //     setAuthUserInfo(response.data)
      //     resolve(response)
      //   }).catch(error => {
      //     reject(error)
      //   })
      // })
    },

    // 登出
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          commit('SET_TOKEN', '')
          removeToken()
          removeAuthUserInfo()
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        removeAuthUserInfo()
        resolve()
      })
    },
  }
}

export default user
